<template>
  <div class="page-container">
    <div class="page-header" style="display: flex; align-items: center; justify-content: space-between;">
      <h1 class="page-title">句子管理</h1>
      <div>
        <el-button type="primary" @click="showBatchImportDialog" style="font-size: 20px; font-weight: bold; letter-spacing: 2px; text-transform: uppercase; height: 48px; min-width: 160px; margin-right: 16px;">
          批量导入
        </el-button>
        <el-button type="primary" @click="showAddDialog" style="font-size: 20px; font-weight: bold; letter-spacing: 2px; text-transform: uppercase; height: 48px; min-width: 160px;">
          添加句子
        </el-button>
      </div>
    </div>
    
    <el-card shadow="hover">
      <div class="filter-container">
        <el-input
          placeholder="搜索句子内容"
          v-model="searchQuery"
          style="width: 300px;"
          clearable
          @keyup.enter.native="handleSearch"
        >
          <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
        </el-input>
      </div>
      
      <el-table
        :data="sentences"
        v-loading="loading"
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="content" label="句子内容"></el-table-column>
        <el-table-column label="录音数量" width="120">
          <template slot-scope="scope">
            {{ scope.row.recording_count || 0 }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleEdit(scope.row)"
              plain
            >编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)"
              plain
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
        >
        </el-pagination>
      </div>
    </el-card>
    
    <!-- 添加/编辑句子对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px" :title-style="{fontSize: '26px', fontWeight: 'bold'}">
      <el-form :model="sentenceForm" :rules="sentenceRules" ref="sentenceForm" label-width="100px" style="font-size: 20px;">
        <el-form-item label="句子内容" prop="content" style="font-size: 20px;">
          <el-input
            type="textarea"
            :rows="4"
            placeholder="请输入句子内容"
            v-model="sentenceForm.content"
            style="font-size: 20px;"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" style="font-size: 20px; min-width: 120px;">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitLoading" style="font-size: 20px; min-width: 120px;">确定</el-button>
      </div>
    </el-dialog>
    
    <!-- 批量导入句子对话框 -->
    <el-dialog title="批量导入句子" :visible.sync="batchImportVisible" width="500px">
      <div style="font-size: 18px; margin-bottom: 20px;">请选择txt文件，每行一个句子</div>
      <el-upload
        ref="upload"
        :action="''"
        :auto-upload="false"
        :show-file-list="true"
        :before-upload="beforeUpload"
        :on-change="handleFileChange"
        :file-list="fileList"
        accept=".txt"
        style="width: 100%;"
      >
        <el-button type="primary" style="font-size: 18px;">选择文件</el-button>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button @click="batchImportVisible = false" style="font-size: 18px; min-width: 100px;">取消</el-button>
        <el-button type="primary" @click="submitBatchImport" :loading="batchImportLoading" style="font-size: 18px; min-width: 100px;">导入</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Sentences',
  data() {
    return {
      sentences: [],
      loading: false,
      submitLoading: false,
      searchQuery: '',
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      dialogVisible: false,
      dialogTitle: '添加句子',
      sentenceForm: {
        id: null,
        content: ''
      },
      sentenceRules: {
        content: [
          { required: true, message: '请输入句子内容', trigger: 'blur' },
          { min: 1, max: 500, message: '长度在1到500个字符之间', trigger: 'blur' }
        ]
      },
      isEdit: false,
      batchImportVisible: false,
      batchImportLoading: false,
      fileList: [],
      batchSentences: []
    }
  },
  created() {
    this.fetchSentences()
  },
  methods: {
    async fetchSentences() {
      this.loading = true
      try {
        const params = {
          page: this.pagination.currentPage,
          limit: this.pagination.pageSize,
          search: this.searchQuery
        }
        
        const result = await this.$store.dispatch('fetchSentences', params)
        console.log('Sentences组件接收到的数据:', result)
        
        // 检查数据结构并适配
        let sentencesList = [];
        if (result && Array.isArray(result.items)) {
          sentencesList = result.items;
          this.pagination.total = result.total;
        } else if (result && Array.isArray(result.sentences)) {
          // 适配API文档中描述的数据结构
          sentencesList = result.sentences;
          this.pagination.total = result.total;
        } else if (Array.isArray(result)) {
          // 如果直接返回数组
          sentencesList = result;
          this.pagination.total = result.length;
        } else {
          console.error('未知的数据结构:', result);
          sentencesList = [];
          this.pagination.total = 0;
        }
        
        // 获取每个句子的录音数量
        for (const sentence of sentencesList) {
          try {
            const count = await this.$store.dispatch('fetchSentenceRecordingCount', sentence.id);
            sentence.recording_count = count;
          } catch (error) {
            console.error(`获取句子 ${sentence.id} 的录音数量失败:`, error);
            sentence.recording_count = 0;
          }
        }
        
        this.sentences = sentencesList;
      } catch (error) {
        console.error('获取句子列表失败:', error)
        this.$errorMessage('获取句子列表失败')
      } finally {
        this.loading = false
      }
    },
    
    handleSearch() {
      this.pagination.currentPage = 1
      this.fetchSentences()
    },
    
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.fetchSentences()
    },
    
    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.fetchSentences()
    },
    
    showAddDialog() {
      this.isEdit = false
      this.dialogTitle = '添加句子'
      this.sentenceForm = {
        id: null,
        content: ''
      }
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.sentenceForm && this.$refs.sentenceForm.clearValidate()
      })
    },
    
    handleEdit(row) {
      this.isEdit = true
      this.dialogTitle = '编辑句子'
      this.sentenceForm = {
        id: row.id,
        content: row.content
      }
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.sentenceForm && this.$refs.sentenceForm.clearValidate()
      })
    },
    
    async handleDelete(row) {
      try {
        await this.$confirm('此操作将永久删除该句子，是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        this.loading = true
        await this.$store.dispatch('deleteSentence', row.id)
        this.$successMessage('删除成功')
        this.fetchSentences()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除句子失败:', error)
          this.$errorMessage('删除句子失败')
        }
      } finally {
        this.loading = false
      }
    },
    
    submitForm() {
      this.$refs.sentenceForm.validate(async valid => {
        if (valid) {
          this.submitLoading = true
          try {
            if (this.isEdit) {
              await this.$store.dispatch('updateSentence', {
                id: this.sentenceForm.id,
                content: this.sentenceForm.content
              })
              this.$successMessage('更新成功')
            } else {
              await this.$store.dispatch('addSentence', {
                content: this.sentenceForm.content
              })
              this.$successMessage('添加成功')
            }
            this.dialogVisible = false
            this.fetchSentences()
          } catch (error) {
            console.error('操作失败:', error)
            this.$errorMessage(this.isEdit ? '更新失败' : '添加失败')
          } finally {
            this.submitLoading = false
          }
        }
      })
    },
    
    showBatchImportDialog() {
      this.batchImportVisible = true
      this.fileList = []
      this.batchSentences = []
    },
    beforeUpload(file) {
      // 只允许txt
      const isTxt = file.type === 'text/plain' || file.name.endsWith('.txt')
      if (!isTxt) {
        this.$errorMessage('只支持txt文件')
      }
      return isTxt
    },
    handleFileChange(file) {
      // 读取文件内容
      const reader = new FileReader()
      reader.onload = (e) => {
        const content = e.target.result
        // 按行分割，去除空行
        this.batchSentences = content.split(/\r?\n/).map(line => line.trim()).filter(line => line)
      }
      if (file.raw) {
        reader.readAsText(file.raw, 'utf-8')
      }
    },
    async submitBatchImport() {
      if (!this.batchSentences.length) {
        this.$errorMessage('请先选择有效的txt文件')
        return
      }
      this.batchImportLoading = true
      try {
        // 假设有store action: batchAddSentences
        await this.$store.dispatch('batchAddSentences', this.batchSentences)
        this.$successMessage('批量导入成功')
        this.batchImportVisible = false
        this.fetchSentences()
      } catch (e) {
        this.$errorMessage('批量导入失败')
      } finally {
        this.batchImportLoading = false
      }
    }
  }
}
</script>

<style scoped>
.filter-container {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style> 